import tkinter as tk

# grid 布局完成计算器页面布局
class MyWindow():
    def __init__(self,app):
        self.app = app
        self.app.title("计算器")

        # 定义一个字符串
        # 对于tk的变量，通过set(值)设置变量，通过get() 获得该变量的值
        self.v = tk.StringVar()
        self.v.set("0")

        # anchor 方向锚点 东:e 南:s 西:w 北:n
        self.label = tk.Label(self.app,textvariable=self.v,width=20,font=("黑体",20),anchor="e")
        self.label.grid(row=0,column=0,columnspan=4)

        self.create_button("7",1,0)
        self.create_button("8", 1, 1)
        self.create_button("9", 1, 2)
        self.create_button("+", 1, 3)

        self.create_button("4", 2, 0)
        self.create_button("5", 2, 1)
        self.create_button("6", 2, 2)
        self.create_button("-", 2, 3)

        self.create_button("1", 3, 0)
        self.create_button("2", 3, 1)
        self.create_button("3", 3, 2)
        self.create_button("*", 3, 3)

        self.create_button(".", 4, 0)
        self.create_button("0", 4, 1)
        self.create_button("C", 4, 2)
        self.create_button("/", 4, 3)

        self.create_button("=", 5, 3)

    def create_button(self,text="",row=0,column=0):
        self.button = tk.Button(self.app, text=text,
                                width=5, font=("黑体", 20),
                                command=lambda:self.on_btn_click(text))
        self.button.grid(row=row, column=column)

    # 设置按钮的点击事件
    def on_btn_click(self,text):
        if self.v.get() == "0":
            self.v.set("")

        if text == "=":
            # 计算结果
            result = eval(self.v.get())
            if result is None:
                return
            self.v.set(str(result))
        elif text == "C":
            # 清空label中的所有内容
            self.v.set("0")

        else:
            self.v.set(self.v.get() + text)


if __name__ == '__main__':
    app = tk.Tk()
    window = MyWindow(app)
    app.mainloop()